
import { join } from 'path';
import  { app, BrowserWindow, Tray, Menu, nativeImage,globalShortcut } from "electron"

let isDev = !app.isPackaged
let url = isDev ? "http://localhost:3011" : 'https://bigscreen.wanhuhealth.com';
let indexFilePath = join(__dirname, "../index.html")
console.log('indexFilePath:',indexFilePath)

function registryShortcut() {
  globalShortcut.register('CommandOrControl+Alt+K', () => {
    // 获取当前窗口
    BrowserWindow!.getFocusedWindow()!.webContents.openDevTools();
  });
}

let iconPath = isDev ? join(__dirname,'..','..','public','city-icon.png') : join(__dirname,'..','city-icon.png')
// 监听electron 加载完毕的时候的创建窗口等等
const createWindow =()=>{
  let win = new BrowserWindow({
    title:'城市福利中心分析室',
    icon: iconPath,
    //fullscreen: true   //全屏
    //frame: false,   	//让桌面应用没有边框，这样菜单栏也会消失
    resizable: true,   //不允许用户改变窗口大小
    width: 1280,         //设置窗口宽高
    height: 800,
    minWidth: 1280,     // 最小宽度
    minHeight: 800,    // 最小高度
    maxWidth: 1920,    // 最大宽度
    maxHeight: 1080,    // 最大高度
    // 进行对首选项的设置
    webPreferences: {
      backgroundThrottling: false,   //设置应用在后台正常运行
      nodeIntegration: true,     //设置能在页面使用nodejs的API
      contextIsolation: false,  //关闭警告信息
      // preload: path.join(__dirname, './preload.js')
    }
  })
 
  
  win.loadURL(url)
  if(!app.isPackaged) {
    win.webContents.openDevTools()
  }
  // 如果打包了，渲染index.html
  // if (app.isPackaged) {
  //   // win.loadFile(indexFilePath);
  // } else {
  //   win.loadURL(url)
  //   win.webContents.openDevTools()
    
  // }

  // 创建托盘对象
  const trayIcon = nativeImage.createFromPath(iconPath)

  const tray = new Tray(trayIcon)
  tray.setToolTip('万户健康-城市福利中心')
  tray.setTitle('城市福利中心')
  tray.on('right-click', () => {
    const template = [
      {
        label: '退出',
        click: () => app.exit()
      }
    ]
    const menuConfig = Menu.buildFromTemplate(template)
    tray.popUpContextMenu(menuConfig)
  })
  tray.on('click', () => {
    console.log('tray click win.isVisible:', win.isVisible())
    if (win.isVisible()) {
      win.hide()
    } else {
      win.show()
    }
    
    win.loadURL(url)
    
  })

  win.on('close', (event:Event) => {
    event.preventDefault()
    win.hide()
  })
}


app.on('ready', function () {
  // 创建一个窗口 设置属性
  createWindow()
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
  if (!isDev) {
    registryShortcut();
  }
})

app.on('window-all-closed', () => {
  console.log('窗口全部关闭了')
  if (process.platform !== "darwin") {
    app.quit();
  }
  globalShortcut.unregisterAll();
})
